<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名称" prop="nodeName">
        <el-input v-model="queryParams.nodeName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="default" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="instanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center" key="id" prop="id">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="id" width="100" align="center" prop="id" :show-overflow-tooltip="true" />
      <el-table-column label="流程名称" align="center" prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="任务名称" width="200" align="center" prop="nodeName" :show-overflow-tooltip="true" />
      <el-table-column label="审批人" align="center" prop="approver" :show-overflow-tooltip="true" />
      <el-table-column label="转办人" align="center" prop="transferredBy" :show-overflow-tooltip="true" />
      <el-table-column label="委派人" align="center" prop="delegate" :show-overflow-tooltip="true" />
      <el-table-column label="流程状态" align="center" prop="flowStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="flow_status" :value="scope.row.flowStatus" />
        </template>
      </el-table-column>
      <el-table-column label="激活状态" align="center" prop="activityStatus" width="140" sortable="custom"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="activityStatus" :value="scope.row.activityStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" link @click="handle(scope.row, false)" type="primary"
            v-hasPermi="['flow:execute:handle']">办理</el-button>
          <el-button size="small" link @click="handle(scope.row, true)" type="primary"
            v-hasPermi="['flow:execute:handle']">任意跳转</el-button>
          <el-button size="small" link @click="transferShow(scope.row, '转办')" type="primary"
            v-hasPermi="['flow:execute:handle']">转办</el-button>
          <el-button size="small" link @click="transferShow(scope.row, '加签')" type="primary"
            v-hasPermi="['flow:execute:handle']">加签</el-button>
          <el-button size="small" link @click="transferShow(scope.row, '委派')" type="primary"
            v-hasPermi="['flow:execute:handle']">委派</el-button>
          <el-button size="small" link @click="transferShow(scope.row, '减签')" type="primary"
            v-hasPermi="['flow:execute:handle']">减签</el-button>
          <el-button size="small" link v-if="scope.row.activityStatus === 0" type="primary"
            @click="toActive(scope.row.instanceId)">激活</el-button>
          <el-button size="small" link v-if="scope.row.activityStatus === 1" type="primary"
            @click="toUnActive(scope.row.instanceId)">挂起</el-button>
          <el-button size="small" link @click="toFlowImage(scope.row.instanceId)" type="primary">流程图</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <component :is="approve" :businessId="businessId" :type="'0'" :taskId="taskId" :showAnyNode="showAnyNode"
      :formId="formPath" @refresh="getList"></component>

    <el-dialog title="流程图" width="70%" v-model="flowChart" append-to-body>
      <WarmChart :insId="insId"></WarmChart>
    </el-dialog>

    <!-- 权限标识：选择用户 -->
    <el-dialog :title="`${dialogTitle}用户选择`" v-if="userVisible" v-model="userVisible" width="80%" append-to-body>
      <selectUser :postParams="postParams" :type="dialogTitle" v-model:selectUser="form.assigneePermission"
        v-model:userVisible="userVisible" @handleUserSelect="handleUserSelect"></selectUser>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance,
    defineAsyncComponent,
    shallowRef
  } from 'vue'
  import * as api from "@/api/flow/execute";
  import {
    active,
    unActive
  } from "@/api/flow/execute";
  import selectUser from "@/views/components/selectUser.vue";
  import WarmChart from "@/views/flow/definition/warm_chart.vue";
  import {
    parseTime
  } from '@/utils/ruoyi'
  import {
    ElMessageBox,
    ElMessage
  } from 'element-plus'
  import {
    useDict
  } from '@/utils/dict'

  const {
    flow_status
  } = useDict('flow_status');
  const activityStatus = ref([{
      label: '挂起',
      value: '0'
    },
    {
      label: '激活',
      value: '1'
    }
  ]);

  // 响应式数据
  const loading = ref(true)
  const flowChart = ref(false)
  const insId = ref(null)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const instanceList = ref([])
  const approve = shallowRef(null)
  const taskId = ref("")
  const businessId = ref("")
  const formPath = ref("")
  const showAnyNode = ref(false)
  const userVisible = ref(false)
  const dialogTitle = ref("")

  // 表单数据
  const form = reactive({
    assigneePermission: null
  })

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    nodeName: '',
    flowStatus: '',
    createTime: []
  })

  // 转办相关参数
  const postParams = reactive({})

  // 生命周期 - 组件挂载后
  onMounted(() => {
    getList()
  })

  /** 查询流程实例列表 */
  const getList = () => {
    try {
      loading.value = true
      api.toDoPage(queryParams).then(response => {
        console.log('todo result', response)
        instanceList.value = response.rows
        total.value = Number(response.total)
      })
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    // 重置查询表单
    Object.keys(queryParams).forEach(key => {
      if (key !== 'pageNum' && key !== 'pageSize') {
        queryParams[key] = null
      }
    })
    handleQuery()
  }

  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }

  /** 办理按钮操作 */
  const handle = (row, showAnyNodeVal) => {
    // 1. 先更新数据
    taskId.value = row.id;
    businessId.value = row.businessId;
    showAnyNode.value = showAnyNodeVal;

    if (!row.formPath) {
      row.formPath = 'system/leave/approve.vue';
    }

    // 3. 再导入组件
    if (row.formCustom === 'N') {
      approve.value = defineAsyncComponent(() => import('@/views/system/leave/approve.vue'));
    } else if (row.formCustom === "Y") {
      formPath.value = row.formPath;
      approve.value = defineAsyncComponent(() => import(`@/views/form/definition/formDialog.vue`));
    }
  };

  // 查看流程图
  const toFlowImage = (instanceId) => {
    insId.value = instanceId
    flowChart.value = true
  }

  /** 转办|加签|委派|减签弹框显示按钮操作 */
  const transferShow = async (row, title) => {
    form.assigneePermission = null
    taskId.value = row.id
    dialogTitle.value = title

    try {
      const res = await api.getTaskById(taskId.value)
      form.assigneePermission = res.data.assigneePermission ? res.data.assigneePermission.split(",") : []
    } catch (error) {
      console.error('获取任务信息失败:', error)
    }

    userVisible.value = true
    const operatorTypeObj = {
      "转办": "1",
      "加签": "6",
      "委派": "3",
      "减签": "7"
    }
    postParams.taskId = row.id
    postParams.operatorType = operatorTypeObj[title]
  }

  // 获取选中用户数据
  const handleUserSelect = async (checkedItemList) => {
    form.assigneePermission = checkedItemList.map(e => e.userId)
    const assigneePermission = [...form.assigneePermission]
    const operatorTypeObj = {
      "转办": "2",
      "加签": "6",
      "委派": "3",
      "减签": "7"
    }

    try {
      await api.interactiveType(
        taskId.value,
        Array.isArray(assigneePermission) ? assigneePermission.join(',') : assigneePermission,
        operatorTypeObj[dialogTitle.value]
      )
      ElMessage.success(`${dialogTitle.value}成功`)
      getList()
    } catch (error) {
      console.error(`${dialogTitle.value}失败:`, error)
      ElMessage.error(`${dialogTitle.value}失败`)
    }
  }

  // 激活流程
  const toActive = async (instanceId) => {
    try {
      await ElMessageBox.confirm(`是否确认激活流程编号为"${instanceId}"的数据项？`)
      await active(instanceId)
      ElMessage.success("激活成功")
      getList()
    } catch (error) {
      // 如果是取消确认，不显示错误信息
      if (error !== 'cancel') {
        console.error('激活流程失败:', error)
        ElMessage.error("激活失败")
      }
    }
  }

  // 挂起流程
  const toUnActive = async (instanceId) => {
    try {
      await ElMessageBox.confirm(`是否确认挂起流程编号为"${instanceId}"的数据项？`)
      await unActive(instanceId)
      ElMessage.success("挂起成功")
      getList()
    } catch (error) {
      // 如果是取消确认，不显示错误信息
      if (error !== 'cancel') {
        console.error('挂起流程失败:', error)
        ElMessage.error("挂起失败")
      }
    }
  }
</script>